package com.weiqiao.mall.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mingsoft.util.StringUtil;
import com.weiqiao.mall.domain.AppUserEntity;
import com.weiqiao.mall.domain.DistributeEntity;
import com.weiqiao.mall.repository.IAppUserRepository;
import com.weiqiao.mall.repository.IDistributeRepository;
import com.weiqiao.mall.service.IDistributeService;
import com.weiqiao.mall.service.mapper.DistributeMapper;
import com.weiqiao.mall.service.vo.DistributeVO;
import org.apache.commons.collections4.CollectionUtils;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.google.gson.Gson;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @author kjy
 */
@Service("DistributeServiceImpl")
public class DistributeServiceImpl implements IDistributeService {

    @Autowired
    private IDistributeRepository distributeRepository;

    @Autowired
    private DistributeMapper distributeMapper;

    @Autowired
    private IAppUserRepository appUserRepository;


    @Autowired
    private AmqpTemplate template;

    @Override
    public DistributeEntity findOne(int company_id) {
        Document document = new Document();
        document.append("company_id", company_id);
        Gson gson = new Gson();
        // 查询分销设置
        String one = distributeRepository.findOne(document);
        if (StringUtil.isBlank(one)) {
            return new DistributeEntity();
        }
        return gson.fromJson(one, DistributeEntity.class);
    }

    @Override
    public boolean updateDistribute(DistributeVO distributeVO) {
        List<DistributeEntity.Commission> commissionList = new ArrayList<>();
        if (!StringUtil.isBlank(distributeVO.getCommission())) {
            // 获取佣金总额
            JSONArray jsonArray = JSONObject.parseArray(distributeVO.getCommission());
            for (int i = 0; i < jsonArray.size(); i++) {
                // 转换对象
                DistributeEntity.Commission commission = jsonArray.getObject(i, DistributeEntity.Commission.class);
                commissionList.add(commission);
            }
        }
        distributeVO.setTotal_commission(commissionList);
        // 实体转换
        DistributeEntity distributeEntity = distributeMapper.toDto(distributeVO);
        Document document = new Document();
        document.append("company_id", distributeVO.getCompany_id());
        distributeRepository.deleteOne(document);
        return distributeRepository.updateOne(document, new Gson().toJson(distributeEntity));
    }

    @Override
    public double getCommission(int company_id, double profit_percent, double amount) {
        // 查询分销设置
        DistributeEntity entity = this.findOne(company_id);
        double amount_percent = 0;
        if (CollectionUtils.isNotEmpty(entity.getTotal_commission())) {
            // 如果当前商品利润比小于设置的第一个利润比则不走配置
            if (!this.compare(profit_percent, entity.getTotal_commission().get(0).getProfit_percent())) {
                return 0;
            }
            // 判断当前利润比符合的区间
            for (int i = 0; i < entity.getTotal_commission().size(); i++) {
                // 大于当前利润比的设置下标-1则是当前利润比符合的区间
                if (!this.compare(profit_percent, entity.getTotal_commission().get(i).getProfit_percent())) {
                    // 获取佣金总额比例
                    amount_percent = entity.getTotal_commission().get(i - 1).getTotal_commission();
                    break;
                }
            }
            // 计算佣金总额
            DecimalFormat df = new DecimalFormat();
            df.applyPattern("#0.00");
            return Double.parseDouble(df.format(amount * amount_percent * 0.01));
        }

        return 0;
    }

    @Override
    public void upgradeMember(int user_id, int company_id) {
        // 获取分销设置
        DistributeEntity distributeEntity = this.findOne(company_id);
        if (StringUtil.isBlank(distributeEntity)) {
            return;
        }
        // 组装查询条件
        Document document = new Document();
        document.append("user_id", user_id);
        AppUserEntity userEntity = this.getAppUserByFilter(document, company_id);
        // 如果是推广会员则返回
        if (StringUtil.isBlank(userEntity) || userEntity.getMember_type() == 2) {
            return;
        }
        // 判断升级标准 0：满足一个1：同时满足
        if (distributeEntity.getUpgrade_standard() == 0) {
            document.append("recommend_id", user_id);
            // 查询下级会员
            int count = appUserRepository.countFruiter(company_id, document);
            Document docMember = new Document();
            // 判断是否满足分销设置条件
            if (count >= distributeEntity.getSatisfy_next_member()) {
                docMember.append("member_type", 2);
                document.remove("recommend_id");
                appUserRepository.updateAppUser(docMember, document, company_id);
                return;
            }
            document.append("member_type", 1);
            // 查询下级消费会员
            int count2 = appUserRepository.countFruiter(company_id, document);
            // 判断是否满足分销设置条件
            if (count2 >= distributeEntity.getSatisfy_next_consumption_member()) {
                docMember.append("member_type", 2);
                document.remove("recommend_id");
                document.remove("member_type");
                appUserRepository.updateAppUser(docMember, document, company_id);
                return;
            }
        } else {
            // 条件为同时满足走消息中间件
//            template.convertAndSend("retail", userEntity);
//            amqpService.sendmsg("retail", userEntity);
        }
    }

    private boolean compare(double a, double b) {
        BigDecimal val1 = new BigDecimal(a);
        BigDecimal val2 = new BigDecimal(b);
        if (val1.compareTo(val2) < 0) {
            return false;
        }
        if (val1.compareTo(val2) == 0) {
            return true;
        }
        if (val1.compareTo(val2) > 0) {
            return true;
        }
        return false;
    }

    // 根据条件查询app用户
    private AppUserEntity getAppUserByFilter(Bson filter, int company_id) {
        String info = appUserRepository.getAppUserByFilter(filter, company_id);
        AppUserEntity entity = new AppUserEntity();
        if (!StringUtil.isBlank(info)) {
            entity = new Gson().fromJson(info, AppUserEntity.class);
        }
        return entity;
    }

}
